package com.societyGames.flashForms
{
import com.societyGames.system.EventObject;

import flash.display.Sprite;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.MouseEvent;
import flash.geom.Rectangle;

public class Draggable extends EventDispatcher
{
  private var _child:Sprite;
  private var _bounds:Rectangle;
  private var _movedEventObject:EventObject;
  private var _droppedEventObject:EventObject;

  public function Draggable(child:Sprite, bounds:Rectangle = null)
  {
    this._movedEventObject = new EventObject(this, "MOVED", Event);
    this._droppedEventObject = new EventObject(this, "DROPPED", Event);
    this._child = child;
    this._bounds = bounds;
    this._child.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
  }

  /**
   * Dispatches Event when the draggable is moved.
   **/
  public function get movedEventObject():EventObject
  {
    return this._movedEventObject;
  }

  /**
   * Dispatches Event when the draggable is dropped or the mouse has moved off.
   **/
  public function get droppedEventObject():EventObject
  {
    return this._droppedEventObject;
  }

  public function get bounds():Rectangle
  {
    return this._bounds;
  }

  public function set bounds(value:Rectangle):void
  {
    this._bounds = value;
  }

  private function mouseDownHandler(event:MouseEvent):void
  {
    this._child.removeEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
    this._child.stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
    this._child.stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
    this._child.startDrag(false, this._bounds);
  }

  private function mouseMoveHandler(event:MouseEvent):void
  {
    this._movedEventObject.dispatchEvent();
  }

  private function mouseUpHandler(event:MouseEvent):void
  {
    this._child.stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMoveHandler);
    this._child.stage.removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
    this._child.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
    this._child.stopDrag();
    this._droppedEventObject.dispatchEvent();
  }
}
}